# 第一阶段：构建
FROM maven:3.9.10-eclipse-temurin-17-alpine AS builder
ARG APP_NAME
ARG APP_VERSION

# 使用阿里云镜像加速依赖下载
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

WORKDIR /app

# 复制自定义的 Maven 配置
COPY .mvn/settings.xml /usr/share/maven/ref/settings-docker.xml

# 单独复制POM文件以利用Docker缓存层
COPY pom.xml .
RUN mvn dependency:go-offline -s /usr/share/maven/ref/settings-docker.xml \
    -Dmaven.main.skip=true \
    -Dmaven.test.skip=true \
    -T 2C

# 复制源代码并构建
COPY src src
RUN mvn package -DskipTests -s /usr/share/maven/ref/settings-docker.xml -T 2C

# 第二阶段：运行时
FROM eclipse-temurin:17-jre-alpine
ARG APP_NAME
ARG APP_VERSION
LABEL app.name=$APP_NAME
LABEL app.version=$APP_VERSION

# 使用非root用户运行
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

WORKDIR /app

# 复制构建产物
COPY --from=builder --chown=appuser:appgroup /app/target/*.jar app.jar

# 优化JVM参数
ENV JAVA_OPTS="-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0 -XX:+AlwaysPreTouch"

# 健康检查优化
HEALTHCHECK --interval=30s --timeout=3s \
  CMD wget --quiet --tries=1 --spider http://localhost:8080/actuator/health || exit 1


EXPOSE 8080

# 使用exec形式启动应用
ENTRYPOINT ["sh", "-c", "exec java $JAVA_OPTS -jar app.jar"]